﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mukhopatro.BusinessLogicLayer;
using Mukhopatro.BusinessEntities;
using Mukhopatro.Helpers;

namespace Mukhopatro.Admin
{
    public partial class admin_login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                litCompanyTitle.Text = "মুখপাত্র";
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            CustomerBLL bll = new CustomerBLL();
            Customer customer = bll.GetCustomer(obj => obj.ClientId == SiteSettings._CLIENT_ID
             && obj.AdminEmail.Equals(txtuserName.Text.Trim()) && obj.AdminPassword.Equals(txtPassword.Text.Trim()));

            if (customer != null && ((!string.IsNullOrEmpty(customer.ClientId) && customer.ClientId.Equals(SiteSettings._CLIENT_ID)) || customer.Role == AdminAccessType.Admin.ToString()))
            {
                HttpCookie cookie = System.Web.Security.FormsAuthentication.GetAuthCookie(customer.AdminEmail, cbxRemember.Checked);
                // Extract the ticket
                System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(cookie.Value);
                // Create the new identity for this request
                System.Web.Security.FormsIdentity identity = new System.Web.Security.FormsIdentity(ticket);
                // Apply it.
                Context.User = new System.Security.Principal.GenericPrincipal(identity, new string[] { "admin" });
                Context.Response.Cookies.Add(cookie);
                System.Web.Security.FormsAuthentication.RedirectFromLoginPage(customer.AdminEmail, cbxRemember.Checked);

                AdminAccessType userType = (AdminAccessType)Enum.Parse(typeof(AdminAccessType), customer.Role);
                if (userType == AdminAccessType.Admin && string.IsNullOrEmpty(customer.ClientId))
                {
                    SessionManager._IS_SUPER_ADMIN = true;
                }
                else
                {
                    SessionManager._IS_SUPER_ADMIN = false;
                }
                SessionManager._LOGGED_IN_CUSTOMER = customer;
                if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ReturnUrl"].ToLower()))
                {
                    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]);
                }
                else
                {
                    HttpContext.Current.Response.Redirect("~/admin/default.aspx");
                }
            }
        }
    }
}